package controleur;

import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import vue.Duck;

public class ControleurCanard implements Runnable {
	// Variable(s) d'instance
	private List<Duck> canards;
	
	// Controleur(s)
	public ControleurCanard() {
		this.canards=new ArrayList<Duck>();
	}

	// Methode(s)
	@Override
	public void run() {
		int x, y, valeur, valeurY;
		while(true) {
			if(this.canards.size() < 1) {
				Random r = new Random();
				valeur = 1 + r.nextInt(3 - 1);
				Dimension dimension = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
				if(valeur == 1) {
					x = 0;
				} else {
					x = (int)dimension.getWidth()-96;
				}
				valeur = r.nextInt((int)dimension.getHeight() -101);
				y = valeur;
				Duck canard = new Duck(x, y);
				int i = 0;
				while(i < this.canards.size()) {
					if(this.collisionPendantAjout(canard, this.canards.get(i))) {
						valeur = r.nextInt((int)dimension.getHeight() -101);
						canard.setY(valeur);
						i=0;
					} else {
						i++;
					}
				}
				if(Controleur.getInstance()!=null) {
					Controleur.getInstance().incrementerMax();
				}
				this.canards.add(canard);
				Controleur.getInstance().getFenetre().addDuck(canard);
			} else {
				for(int i = 0; i < this.canards.size(); i++) {
					Duck d = this.canards.get(i);
					if(d.isDead()) {
						d.setY(d.getY()+5);
					} else {
						if(d.getSigne()==1) {
							d.setX(d.getX()+5);
						} else {
							d.setX(d.getX()-5);
						}
						if(d.getSigneY()==1) {
							d.setY(d.getY()+5);
						} else {
							d.setY(d.getY()-5);
						}
						d.gererAiles();
					}
				}
				try {
					Thread.sleep(13);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				int j = 0;
				while(j < this.canards.size()) {
					if(!this.canards.get(j).isVisible()) {
						Controleur.getInstance().getFenetre().getPanel().remove(this.canards.get(j));
						this.canards.remove(j);
					} else {
						j++;
					}
				}
			}
		}
	}
	
	public List<Duck> getCanards (){
		return this.canards;
	}
	
	public boolean collisionPendantAjout(Duck d1, Duck d2) {
		if(d1.getY() >= d2.getY() && d1.getY() <= (d2.getY()+51)) {
			return true;
		}
		if((d1.getY()+51) >= d2.getY() && (d1.getY()+51) <= (d2.getY()+51)) {
			return true;
		}
		return false;
	}
}
